#!/usr/bin/env python
#-*- coding: utf-8 -*-

import hashlib

class Album:
    
    def __init__(self, dir):
        self.dir = dir
        self.new_dir = dir
        self.tracks = []
        self.avg_bitrate = 0.0
        self.album_hash = None
        
        self.status = None
        self.distance = 0.0
        self.best_candidate = None
        self.finalize = False
        
        self.format = None
        self.new_format = None
        self.need_conversion = False
        return
    
    def __repr__(self):        
        outList = []
        outList.append('\n[' + str(self.status) + '][' + str(self.finalize) + '] ' + self.dir + ' ' + str(self.avg_bitrate))
        for track in self.tracks:
            outList.append(track.__repr__())
        return '\n'.join(outList)    
    
    def get_durations(self):
        durations = []        
        for track in self.tracks:
            durations.append(track['tracklength'])
        return durations
    
    def get_track_number(self):
        return len(self.tracks)
    
    def get_track(self, track_number):
        for track in self.tracks:
            if track['trackposition'] == track_number:
                return track
            
    def get_best_candidate_track(self, track_number):
        for track in self.best_candidate:
            # cast to int is needed because musicbrainz returns unicode
            if int(track['trackposition']) == track_number:
                return track
        
    def create_hash(self):
        m = hashlib.md5()
        m.update(self.best_candidate[0]['albumauthors'] + self.best_candidate[0]['albumtitle'] + self.best_candidate[0]['trackmedium'])
        self.album_hash = m.digest()

    def create_dict(self):
        if self.status == 'MATCH':
            album_dict = {'path' : self.dir,
                          'status' : self.status,
                          'author' : self.best_candidate[0]['albumauthors'],
                          'title' : self.best_candidate[0]['albumtitle'],
                          'finalize' : 1,
                          'type' : 'album'}
            return album_dict
        else:
            album_dict = {'path' : self.dir,
                          'status' : self.status,
                          'author' : 'Not Found',
                          'title' : 'Not Found',
                          'finalize' : 0,
                          'type' : 'album'}
            return album_dict
